package com.coder.user.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject:coder_parent
 * @BelongsPackage:com.coder.user.interceptor
 * @Author:linchong
 * @CreateTime:2019-01-14 10:48
 * @Description:拦截器，处理用户jwt操作权限
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经历的拦截器");
        //无论如何都放行，具体能不能操作还是在具体的操作中去判断
         //拦截器只是负责把请求头中包含的token的令牌进行一个解析
        String header = request.getHeader("Authorization");  //获取请求头信息中token信息

        if(header!=null && !"".equals(header)){
            //如果包含有Authorization头信息，就对其进行解析，没有就放行
            if(header.startsWith("bearer ")){
                //得到令牌
                String token = header.substring(7);
                //对令牌进行验证
                try{
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if(roles != null&&roles.equals("admin")){
                        request.setAttribute("claims_admin",token);
                    }
                    if(roles != null&&roles.equals("user")){
                        request.setAttribute("claims_user",token);
                    }
                }catch (Exception e){
                    throw new RuntimeException("令牌不正确！");
                }
            }
        }

        return true;
    }
}
